import sys
from PyQt5.QtWidgets import * #导入PyQt相关模块
from PyQt5.QtGui import *
from PyQt5.QtCore import *
#from pyqtgraph.graphicsItems import *
import pyqtgraph as pg
import math
from gui import * #导入窗口
import numpy as np
from PIL import Image #pillow

global dir_str
global scene,scene_buf,scene_buf2,vb
global item
global pic
global grayimg#Gray picture
global imgarray
global frame
global roi_befor
global roi_after

#class Mywindow(QMainWindow,Ui_Form):   #使用这个的话界面布局会乱
class roiwidge(QWidget,Ui_Form):#界面布局自动缩放
    def __init__(self,parent=None):
        super(roiwidge,self).__init__(parent)
        
        self.setupUi(self)
        self.setWindowTitle("ROI")
        #self.setWindowIcon(QIcon(r'D:\My\zry\software\pyqt5\tp.ico'))
        self.graphicsView.mouseReleaseEvent = self.gpmouseReleaseEvent
        self.graphicsView.mousePressEvent = self.gpmousePressEvent
        self.graphicsView.mouseDoubleClickEvent = self.gpmouseDoubleClickEvent
        self.graphicsView.mouseMoveEvent = self.gpmousemoveEvent
        
        self.loadButton.clicked.connect(self.load_click)
        self.loadButton.setText("Select File")
        self.ClearROIButton.clicked.connect(self.ClearAllROI)#清除界面所有ROI
        self.SetRoiColor.clicked.connect(self.SetRoiColorclick)
        self.SavePic.clicked.connect(self.savepic)
        self.SaveData.clicked.connect(self.savedata)
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)#整行选择
        self.tableWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)#允许右键子菜单
        self.tableWidget.customContextMenuRequested.connect(self.tableWidget_V_menu)#右键菜单操作
        self.RectROI.setChecked(True)
        self.lastPoint = QPoint()

        self.endPoint = QPoint()
        self.PenColor = QColor("white")
        self.points = list()#仅多边形使用
        self.name = list()
        self.link_list = list()
        self.MultiRoiDone = False
        self.multiroi_count = 0
        self.start_pos = QPoint(0,0)
        self.end_pos = QPoint(0,0)
        self.movedone = False
        self.drawing = False
    def load_click(self):#选择图像文件路径
        global dir_str
        global scene
        global scene_buf
        global scene_buf2
        global roi_befor
        global vb
        global item
        global pic
        global grayimg#Gray picture
        global imgarray
        #self.listWidget.clear()#清空界面缓存
        self.tableWidget.clear()
        self.tableWidget.setHorizontalHeaderLabels(['ROI','Mean','Dimensions'])#设置表头文字
        # print(self.tableWidget.rowCount())
        # self.tableWidget.setRowCount(1)
        # self.tableWidget.setItem(0,0,QTableWidgetItem("测试1"))
        # self.tableWidget.setItem(0,1,QTableWidgetItem("测试2"))
        #self.filelocation.setText("测试界面")
        #self指向自身，"Open File"为文件名，"./"为当前路径，最后为文件类型筛选器
        fname,ftype = QFileDialog.getOpenFileName(self, "Open File", "C:", "All(*.*);;tiff(*.tiff);;png(*.png);;jpg(*.jpg)")#如果添加一个内容则需要加两个分号
        # 该方法返回一个tuple,里面有两个内容，第一个是路径， 第二个是要打开文件的类型，所以用两个变量去接受
        # 如果用户主动关闭文件对话框，则返回值为空
        if fname[0]:  # 判断路径非空
            dir_str = fname
            buf = fname
            buf = buf.replace("\\", "/")
            self.setWindowTitle("ROI--" + buf)
            #show picture
            #pic = QtGui.QPixmap(dir_str)
            grayimg = Image.open(dir_str).convert('L')
            #grayimg.show()
            imgarray = np.asarray(grayimg)
            size_x = len(imgarray[0])
            size_y = len(imgarray)
            qimg = QImage(dir_str)
            pic = QPixmap.fromImage(qimg)
            #img.show()
            item = QGraphicsPixmapItem(pic)
            scene = QGraphicsScene(0,0,size_x,size_y)
            roi_befor = 0
            roi_after = 0
            scene_buf = pg.ImageItem()
            scene_buf.setImage(imgarray)
            vb = pg.ViewBox()
            vb.addItem(scene_buf)
            #scene_buf = QGraphicsScene(0,0,size_x,size_y)
            scene.addItem(item)
            #scene_buf.addItem(item)
            self.graphicsView.setScene(scene)
    #鼠标滚轮        
    def wheelEvent(self, event):
        self.scaleView(math.pow(2.0,event.angleDelta().y() / 240.0))
        pass
    #图片缩放
    def scaleView(self,scaleFactor):
        factor = self.graphicsView.transform().scale(scaleFactor,scaleFactor).mapRect(QRectF(0,0,1,1)).width()
        if (factor < 0.07 or factor > 100 ):
            return
        self.graphicsView.scale(scaleFactor,scaleFactor)
    #鼠标事件
    def gpmousePressEvent(self,event):
        if self.MoveROI.isChecked() == True:#移动
            if event.button() == QtCore.Qt.LeftButton:
                self.movedone = True
                self.tableWidget.clearSelection()
            else:
                pass
        else:
            if event.button() == QtCore.Qt.LeftButton:#左键
                self.MultiRoiDone = False
                point = self.graphicsView.mapToScene(event.pos())
                if self.MultiRectROI.isChecked() == True:#多边形
                    self.points.append(point)
                    self.draw_roi(points=self.points)
                else:
                    self.lastPoint = point
            elif event.button() == QtCore.Qt.RightButton:
                if self.MultiRectROI.isChecked():
                    self.MultiRoiDone = True
                    self.draw_roi(points=self.points)
                else:
                    pass
            #self.RectROI.setChecked(True)
        #event.accept()
    def gpmouseReleaseEvent(self,event):
        if self.MoveROI.isChecked() == True:#移动
            if event.button() == QtCore.Qt.LeftButton:
                self.end_pos = self.graphicsView.mapToScene(event.pos())#记录结束位置
                #print(self.start_pos,self.end_pos)
                self.start_pos = QPoint(0,0)
            else:
                pass
        elif self.MultiRectROI.isChecked() == False:#非多边形
            if event.button() == QtCore.Qt.LeftButton:
                #print("release left")
                #self.drawing = False
                point = self.graphicsView.mapToScene(event.pos())
                self.endPoint = point

                self.drawing = not self.drawing
                if self.drawing ==True:
                    if self.RectROI.isChecked() == True:
                        self.start_draw_recroi(self.lastPoint)
                    elif self.CircleROI.isChecked() == True:
                        self.start_draw_ellipseroi(self.lastPoint)
                #(x,y,w,h) = self.caculat_Rec(self.lastPoint,self.endPoint)
                #self.draw_roi((x,y),(w,h))
            else:
                pass
                #print(event.buttons())
        else:
            pass

    def gpmouseDoubleClickEvent(self,event):
        pass
    def gpmousemoveEvent(self,event):
        row_num = self.get_select_item()
        if (self.MoveROI.isChecked() == True) and (row_num >= 0) :
            roi = self.link_list[row_num][1]
            text = self.link_list[row_num][2]
            pos = self.graphicsView.mapToScene(event.pos())
            buf = pg.PolyLineROI([])#
            if type(roi) != type(buf):#pg.graphicsItems.ROI.PolyLineROI:
                roi.setPos((pos.x()),(pos.y()))
                text.setPos((pos.x()),(pos.y()-20))
                self.update_avg_realtime(roi,row_num)
                roi.setPen(width=1, color=self.PenColor)
                text.setColor(self.PenColor)
            else:#任意多边形不支持移动
                pass
        elif (self.RectROI.isChecked() == True) and (self.drawing == True) :
            pos = self.graphicsView.mapToScene(event.pos())
            self.draw_recroi(pos)
        elif (self.CircleROI.isChecked() == True) and (self.drawing == True):
            pos = self.graphicsView.mapToScene(event.pos())
            self.draw_ellicpseroi(pos)
        else:
            pass
    #计算矩形ROI的原点和长宽
    def caculat_Rec(self,pos1,pos2):
        x1 = pos1.x()
        x2 = pos2.x()
        y1 = pos1.y()
        y2 = pos2.y()
        #print(x1,x2,y1,y2)
        if x1 >= x2:
            x = x2
        else :
            x = x1
        if y1 >= y2:
            y = y2
        else :
            y = y1
        h = abs(y1-y2)
        w = abs(x1-x2)
        return x,y,w,h
    #ROI
    def draw_roi(self,pos=(0,0),size=(0,0),points=list()):
        global frame
        global scene
        global scene_buf
        global roi_befor
        global roi_after
        global vb
        if self.RectROI.isChecked() == True:
            frame = pg.RectROI(pos,size)
            self.name.append("roi{}".format(len(self.name)+1))
            frame.setPen(width=1, color=self.PenColor)
            scene.addItem(frame)
            frame1 = pg.TextItem(self.name[-1])#添加字符显示
            frame1.setPos(pos[0],pos[1]-20)
            frame1.setColor(self.PenColor)
            scene.addItem(frame1)           
            self.link_list.append([self.name[-1],frame,frame1])
            #print(pos,size)
            buf = imgarray[int(pos[1]):int(pos[1]+size[1]),int(pos[0]):int(pos[0]+size[0])]
            self.Caculat_Info(buf)
        elif self.CircleROI.isChecked() == True:
            #frame = pg.CircleROI(pos,size)  #EllipseROI
            frame = pg.EllipseROI(pos,size)
            self.name.append("roi{}".format(len(self.name)+1)) 
            frame.setPen(width=1, color=self.PenColor)     
            scene.addItem(frame)
            frame1 = pg.TextItem(self.name[-1])#添加字符显示
            frame1.setPos(pos[0],pos[1]-20)
            frame1.setColor(self.PenColor)
            scene.addItem(frame1)           
            self.link_list.append([self.name[-1],frame,frame1])
            vb.addItem(frame)
            buf,mask = frame.getArrayRegion(imgarray,scene_buf,axes=(1, 0))#此处修改了库函数2022年4月29日
            vb.removeItem(frame)
            scene.addItem(frame)
            self.Caculat_CircleInfo(buf,mask)
        elif self.MultiRectROI.isChecked() == True:
            if self.MultiRoiDone:
                frame = pg.PolyLineROI([])
                #frame = pg.PolyLineROI(points).setPoints(points,closed=True)
                frame.setPoints(points,closed=True)
                self.name.append("roi{}".format(len(self.name)+1))
                #frame.addTranslateHandle((0,0),name=self.name[-1],index=len(self.name)-1)
                #获取ROI区域
                mask,buf = self.Get_MultiROIMask(imgarray,points)
                self.multiroi_count = 0
                roi_after = len(scene.items())
                for i in range(roi_after-roi_befor):#remove Duplicate ROI item
                    scene.removeItem(scene.items()[0])    
                frame.setPen(width=1, color=self.PenColor)           
                scene.addItem(frame)
                mask1 = np.transpose(mask)
                frame1 = pg.TextItem(self.name[-1])#添加字符显示
                frame1.setPos(points[0].x(),points[0].y()-20)
                frame1.setColor(self.PenColor)
                scene.addItem(frame1)               
                self.link_list.append([self.name[-1],frame,frame1])
                self.Caculat_CircleInfo(buf,mask1)
                self.points.clear()
            else:
                if self.multiroi_count == 0 :
                    roi_befor = len(scene.items())                       
                self.multiroi_count = self.multiroi_count + 1
                frame = pg.PolyLineROI(points)
                frame.setPen(width=1, color=self.PenColor)
                scene.addItem(frame)
    # def draw_recroi(self,pos_now):
    #     handle = self.link_list[-1][1]#获取新建ROI的句柄
    #     pos = handle.pos()
    #     x,y,w,h = self.caculat_Rec(pos,pos_now)
    #     handle.setSize((w,h))
    #     index = len(self.link_list) - 1
    #     self.update_avg_realtime(handle,index)
    def draw_recroi(self,pos_now):
        handle = self.link_list[-1][1]#获取新建ROI的句柄
        handletext = self.link_list[-1][2]#获取新建ROI的text句柄
        pos = self.lastPoint
        pos_x = pos.x()
        pos_y = pos.y()
        pos_now_x = pos_now.x()
        pos_now_y = pos_now.y()
        minP = QPointF()
        maxP = QPointF()
        if pos_now_x < pos_x:
            minP.setX(pos_now_x)
            maxP.setX(pos_x)
        else:
            minP.setX(pos_x)
            maxP.setX(pos_now_x)
        if pos_now_y < pos_y:
            minP.setY(pos_now_y)
            maxP.setY(pos_y)
        else:
            minP.setY(pos_y)
            maxP.setY(pos_now_y)
        x,y,w,h = self.caculat_Rec(minP,maxP)
        handle.setSize((w,h))
        handle.setPos(minP)
        textP = QPointF(minP.x(),minP.y()-20)
        handletext.setPos(textP)
        index = len(self.link_list) - 1
        self.update_avg_realtime(handle,index)
    # def draw_ellicpseroi(self,pos_now):
    #     handle = self.link_list[-1][1]#获取新建ROI的句柄
    #     pos = handle.pos()
    #     x,y,w,h = self.caculat_Rec(pos,pos_now)
    #     handle.setSize((w,h))
    #     index = len(self.link_list) - 1
    #     self.update_avg_realtime(handle,index)
    def draw_ellicpseroi(self,pos_now):
        handle = self.link_list[-1][1]#获取新建ROI的句柄
        handletext = self.link_list[-1][2]#获取新建ROI的text句柄
        pos = self.lastPoint
        pos_x = pos.x()
        pos_y = pos.y()
        pos_now_x = pos_now.x()
        pos_now_y = pos_now.y()
        minP = QPointF()
        maxP = QPointF()
        if pos_now_x < pos_x:
            minP.setX(pos_now_x)
            maxP.setX(pos_x)
        else:
            minP.setX(pos_x)
            maxP.setX(pos_now_x)
        if pos_now_y < pos_y:
            minP.setY(pos_now_y)
            maxP.setY(pos_y)
        else:
            minP.setY(pos_y)
            maxP.setY(pos_now_y)
        x,y,w,h = self.caculat_Rec(minP,maxP)
        handle.setSize((w,h))
        handle.setPos(minP)
        textP = QPointF(minP.x(),minP.y()-20)
        handletext.setPos(textP)
        index = len(self.link_list) - 1
        self.update_avg_realtime(handle,index)
    def start_draw_recroi(self,pos):#先创建size=(1,1)的初始ROI，再根据handle实时调整大小
        global frame
        global scene
        size = (1,1)
        frame = pg.RectROI(pos,size)
        self.name.append("roi{}".format(len(self.name)+1))
        frame.setPen(width=1, color=self.PenColor)
        scene.addItem(frame)
        frame1 = pg.TextItem(self.name[-1])#添加字符显示
        #frame1.setPos(pos[0],pos[1]-20)
        frame1.setPos(pos.x(),pos.y()-20)
        frame1.setColor(self.PenColor)
        scene.addItem(frame1)           
        self.link_list.append([self.name[-1],frame,frame1])  
        self.Add_tableWidget(0,0) 
    def start_draw_ellipseroi(self,pos):
        global frame
        global scene
        size = (1,1)
        frame = pg.EllipseROI(pos,size)
        self.name.append("roi{}".format(len(self.name)+1))
        frame.setPen(width=1, color=self.PenColor)
        scene.addItem(frame)
        frame1 = pg.TextItem(self.name[-1])#添加字符显示
        #frame1.setPos(pos[0],pos[1]-20)
        frame1.setPos(pos.x(),pos.y()-20)
        frame1.setColor(self.PenColor)
        scene.addItem(frame1)           
        self.link_list.append([self.name[-1],frame,frame1])  
        self.Add_tableWidget(0,0) 
    #Set ROI color
    def SetRoiColorclick(self):
        self.PenColor = QColorDialog.getColor()
        for handle in self.link_list:
            handle[1].setPen(width=1, color=self.PenColor)
            handle[2].setColor(self.PenColor)
    def Caculat_Info(self,piclist):
        sum = 0
        count = 0
        avg = 0
        for xlist in piclist:
            for ylist in xlist:
                sum = sum + ylist
                count = count + 1
        avg = sum /count
        self.Add_tableWidget(avg,count)
        #self.listWidget.addItem(self.name[-1]+"average is:"+str(avg))
        #self.tableWidget.items().append(avg)
    def ClearAllROI(self):
        global scene
       # self.listWidget.clear()#清空界面缓存
        self.tableWidget.clear()
        self.tableWidget.setHorizontalHeaderLabels(['ROI','Mean','Dimensions'])#设置表头文字
        self.tableWidget.setRowCount(0)
        self.points.clear()
        self.name.clear()
        self.link_list.clear()
        #del scene.items()[0:-1]
        for i in range(len(scene.items())-1):
            scene.removeItem(scene.items()[0])
        #print(scene.items())
    def Caculat_CircleInfo(self,data,mask):
        mask1 = np.transpose(mask)
        sum = 0
        count = 0
        avg = 0
        for i in range(len(mask1)-1):
            for j in range(len(mask1[0])-1):
                if mask1[i,j]:
                    sum = sum + data[i,j]
                    count = count + 1
        avg = sum / count
        self.Add_tableWidget(avg,count)
        #self.listWidget.addItem(self.name[-1]+"average is:"+str(avg))
    #判断点在多边形范围内，其中pt为点，poly为多边形区域
    #版权声明：本文为CSDN博主「可可爱爱的小肥肥」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
    #原文链接：https://blog.csdn.net/ftmsz12345678/article/details/115375461
    def isInsidePolygon(self,pt, poly):
        c = False
        i = -1
        l = len(poly)
        j = l - 1
        while i < l - 1:
            i += 1
            if((poly[i][0]<=pt[0] and pt[0] < poly[j][0])or(
                poly[j][0]<=pt[0] and pt[0]<poly[i][0] )):
                if(pt[1]<(poly[j][1]-poly[i][1]) * (pt[0]-poly[i][0])/(
                    poly[j][0]-poly[i][0])+poly[i][1]):
                    c = not c
            j=i
        return c
    def Get_MultiROIMask(self,picbuf,points):#picbuf传入整幅图像二维数组，points传入原始坐标列表
        max_x = 0
        max_y = 0
        picbuf1 = np.transpose(picbuf)
        min_x = len(picbuf1)#行数量
        min_y = len(picbuf1[0])#列数量
        point_list = np.zeros((len(points),2))
        for i in range(len(points)):
            point_list[i][0] = points[i].x()
            point_list[i][1] = points[i].y()
            if points[i].x() >= max_x:
                max_x = points[i].x()
            if points[i].y() >= max_y:
                max_y = points[i].y()
            if points[i].x() <= min_x:
                min_x = points[i].x()
            if points[i].y() <= min_y:
                min_y = points[i].y()
        #截取多边形所在矩形区域像素值并进行坐标平移
        minx_t = int(min_x)
        miny_t = int(min_y)
        maxx_t = int(max_x)
        maxy_t = int(max_y)
        picbuf1 = picbuf1[minx_t:(maxx_t+1),miny_t:(maxy_t+1)]
        for i in range(len(points)):
            point_list[i][0] = point_list[i][0] - minx_t
            point_list[i][1] = point_list[i][1] - miny_t
        mask_buf = np.zeros(((maxx_t-minx_t),(maxy_t-miny_t)))#根据多边形所在矩形区域大小创建全0mask,减少计算量
        for x in range(len(picbuf1)):
            for y in range(len(picbuf1[0])):
                if self.isInsidePolygon((x,y),point_list):
                    mask_buf[x][y] = 1
        return (mask_buf,picbuf1)
    def Add_tableWidget(self,avg,count):#列表显示
        a = self.tableWidget.rowCount()
        self.tableWidget.setRowCount(a+1)
        #print(self.tableWidget.rowCount())
        self.tableWidget.setItem(a,0,QTableWidgetItem(str(self.name[-1])))
        self.tableWidget.setItem(a,1,QTableWidgetItem(str('%.2f' % avg)))
        self.tableWidget.setItem(a,2,QTableWidgetItem(str('%.2f' % count)))
    def tbmousePressEvent(self,event):
        pass
    def tableWidget_V_menu(self,pos):
        row_num = -1
        rect_buf = pg.RectROI((0,0),(0,0))
        ellipse_buf = pg.EllipseROI((0,0),(0,0))
        for i in self.tableWidget.selectionModel().selection().indexes():
            row_num = i.row()
        if row_num < self.tableWidget.rowCount():
            menu = QMenu()
            if (type(self.link_list[row_num][1]) == type(rect_buf)) or (type(self.link_list[row_num][1]) == type(ellipse_buf)):
                item1 = menu.addAction(u"Delete")
                item2 = menu.addAction(u"Copy")
            else:
                item1 = menu.addAction(u"Delete")
            action = menu.exec_(self.tableWidget.mapToGlobal(pos))
        else:
            return
        if action == item1:
            self.Delete_select_roi(row_num)
        elif action == item2:
            self.Copy_select_roi(row_num)
        else:
            pass
    def Delete_select_roi(self,index):
        link = self.link_list[index]
        # for item in scene.items():
        #     print(item)
        scene.removeItem(self.link_list[index][1])#ROI
        scene.removeItem(self.link_list[index][2])#TEXT
        total = len(scene.items())
        # for item in scene.items():
        #     print(item)
        self.tableWidget.removeRow(index)
        #self.name.pop(index)
        self.link_list.pop(index)
    def Copy_select_roi(self,row_num):
        roi = self.link_list[row_num][1]
        pos = roi.pos()+ (20,20)
        size = roi.size()
        rect_buf = pg.RectROI((0,0),(0,0))
        ellipse_buf = pg.EllipseROI((0,0),(0,0))
        avg = 0
        if type(roi) == type(rect_buf):
            frame = pg.RectROI(pos,size)
            self.name.append("roi{}".format(len(self.name)+1))
            frame.setPen(width=1, color=self.PenColor)
            scene.addItem(frame)
            frame1 = pg.TextItem(self.name[-1])#添加字符显示
            frame1.setPos(pos[0],pos[1]-20)
            frame1.setColor(self.PenColor)
            scene.addItem(frame1)           
            self.link_list.append([self.name[-1],frame,frame1])
            avg,count = self.update_RecROI(frame)

            self.Add_tableWidget(avg,count)
            
        elif type(roi) == type(ellipse_buf):
            frame = pg.EllipseROI(pos,size)
            self.name.append("roi{}".format(len(self.name)+1)) 
            frame.setPen(width=1, color=self.PenColor)     
            scene.addItem(frame)
            frame1 = pg.TextItem(self.name[-1])#添加字符显示
            frame1.setPos(pos[0],pos[1]-20)
            frame1.setColor(self.PenColor)
            scene.addItem(frame1)           
            self.link_list.append([self.name[-1],frame,frame1])
            avg,count = self.update_EllipseRoi(frame)
            self.Add_tableWidget(avg,count)
        else:
            pass
    def get_select_item(self):
        row_num = -1
        try:
            for i in self.tableWidget.selectionModel().selection().indexes():
                row_num = i.row()
            if row_num < self.tableWidget.rowCount():
                return row_num
            else:
                return -1
        except Exception as ex:
            return -1
    def update_avg_realtime(self,roi,index):#随着拖动动态更新计算值
        rect_buf = pg.RectROI((0,0),(0,0))
        ellipse_buf = pg.EllipseROI((0,0),(0,0))
        if type(roi) == type(rect_buf):#矩形
            avg,count = self.update_RecROI(roi)
            self.tableWidget.setItem(index,1,QTableWidgetItem(str('%.2f' % avg)))
            self.tableWidget.setItem(index,2,QTableWidgetItem(str('%.2f' % count)))
        elif type(roi) == type(ellipse_buf):
            #pass
            avg,count = self.update_EllipseRoi(roi)
            self.tableWidget.setItem(index,1,QTableWidgetItem(str('%.2f' % avg)))
            self.tableWidget.setItem(index,2,QTableWidgetItem(str('%.2f' % count)))
        else:
            pass
    def update_RecROI(self,roi):
        pos = roi.pos()
        size = roi.size()
        buf = imgarray[int(pos[1]):int(pos[1]+size[1]),int(pos[0]):int(pos[0]+size[0])]
        sum = 0
        count = 0
        avg = 0
        for xlist in buf:
            for ylist in xlist:
                sum = sum + ylist
                count = count + 1
        avg = sum /count
        return (avg,count)
    def update_EllipseRoi(self,roi):
        global imgarray
        global scene_buf
        global vb
        pos = roi.pos()
        size = roi.size()
        frame = pg.EllipseROI(pos,size)
        vb.addItem(frame)
        buf,mask = frame.getArrayRegion(imgarray,scene_buf,axes=(1, 0))#此处修改了库函数2022年4月29日
        vb.removeItem(frame)
        mask1 = np.transpose(mask)
        sum = 0
        count = 0
        avg = 0
        for i in range(len(mask1)-1):
            for j in range(len(mask1[0])-1):
                if mask1[i,j]:
                    sum = sum + buf[i,j]
                    count = count + 1
        avg = sum / count  
        return avg,count      
    def savepic(self):
        if self.tableWidget.rowCount() > 0 :
            pname = QFileDialog.getExistingDirectory(self,"Select Folder","/")
            text = self.windowTitle();
            text1 = text.split('/')
            text2 = text1[-1]
            text3 = list(text2)
            text3.insert(text3.index('.'),'_ROI')
            text4 = "".join(text3)
            #text5 = "".join(pname)
            save_str = pname + text4
            rect = scene.sceneRect()
            #pixmap = QtGui.QImage(rect.height(),rect.width(),QImage.Format.Format_ARGB32_Premultiplied)
            #pixmap = QImage()
            pixmap = QtGui.QPixmap(rect.width(),rect.height())
            painter = QtGui.QPainter(pixmap)
            rectf = QRectF(0,0,pixmap.rect().width(),pixmap.rect().height())
            scene.render(painter,rectf,rect)
            painter.end()
            #dir = pname + '/1.pnd'
            pixmap.save(save_str)
        else :
            QMessageBox.warning(self, 'Warning', 'There is nothing to be saved.', QMessageBox.Close)
    def savedata(self):
        index = self.tableWidget.rowCount()
        item = list()
        if index > 0 :
            pname = QFileDialog.getExistingDirectory(self,"Select Folder","/")
            text = self.windowTitle();
            text1 = text.split('/')
            text2 = text1[-1]
            text3 = list(text2)
            text3.insert(text3.index('.'),'_ROI')
            text4 = "".join(text3)
            text5 = pname + text4
            save_str = text5[:text5.index('.')]+'.txt'
            fw = open(save_str, 'w')
            #title
            fw.write("ROI\t")
            fw.write("Mean\t")
            fw.write("Dimension\n")
            for i in range(index):
                item.append(self.tableWidget.item(i, 0).text())
                fw.write(self.tableWidget.item(i, 0).text())
                fw.write("\t")
                item.append(self.tableWidget.item(i, 1).text())
                fw.write(self.tableWidget.item(i, 1).text())
                fw.write("\t")
                item.append(self.tableWidget.item(i, 2).text())
                fw.write(self.tableWidget.item(i, 2).text())
                fw.write("\n")
            print(item)
            fw.close()
        else:
            QMessageBox.warning(self, 'Warning', 'There is nothing to be saved.', QMessageBox.Close)
if __name__=='__main__':
    app = QApplication(sys.argv)
    myWin = roiwidge()
    myWin.show()
    sys.exit(app.exec_())

